using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;

namespace GetTogether.Studio.Web
{
    public class LoggingsHelper
    {
        public static string GetPage(string url)
        {
            HttpWebRequest r = (HttpWebRequest)WebRequest.Create(url);
            r.SendChunked = false;
            r.Method = "GET";
            r.KeepAlive = true;
            r.Referer = url;
            r.Accept = "text/html, application/xml;q=0.9, application/xhtml xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1";
            r.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0";
            r.ContentType = "text/html; charset=UTF-8";
            string result = GetTogether.Utility.RequestHelper.GetResponse(r.GetResponse());
            return result;
        }

        public static Loggings GetLoggings(string url)
        {
            string page = GetPage(url);
            if (string.IsNullOrEmpty(page)) return null;
            Regex regx = new Regex(@"(?<Link><[a|A]{1} [HREF|href]{4}=""(?<Href>.*)"">(?<Name>.*)<\/[a|A]{1}>)", RegexOptions.None);
            MatchCollection matchs = regx.Matches(page);
            Loggings result = new Loggings();
            foreach (Match m in matchs)
            {
                if (m.Success)
                {
                    Loggings.Logging log = new Loggings.Logging();
                    log.Href = m.Groups["Href"].Value;
                    log.Name = m.Groups["Name"].Value;
                    if (!string.IsNullOrEmpty(log.Href) && !string.IsNullOrEmpty(log.Name) && log.Href.Trim() != "/")
                    {
                        log.IsFile = !log.Href.EndsWith("/");
                        result.Add(log);
                    }
                }
            }
            return result;
        }

        public class Loggings : GetTogether.ObjectBase.ListBase<Loggings.Logging>
        {
            public Loggings()
            {
            }

            public class Logging
            {
                public string Name;
                public string Href;
                public bool IsFile = false;
                public Logging()
                {
                }
            }
        }
    }
}
